/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.membermsg.service.impl.MemberMsgServiceImpl
   Module Description   :

   Date Created      : 2010/12/29
   Original Author   : cut7man
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.membermsg.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.sms.entity.Sms;
import com.yaodian100.core.sms.service.SmsService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.common.EnvParameters;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.membermsg.entity.MailTemp;
import com.yaodian100.ec.membermsg.entity.MemberMsg;
import com.yaodian100.ec.membermsg.entity.MemberMsgTemplate;
import com.yaodian100.ec.membermsg.entity.SmsTemp;
import com.yaodian100.ec.membermsg.service.MemberMsgService;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.product.entity.Product;

/**
 * @author cut7man
 * 
 */
public class MemberMsgServiceImpl implements MemberMsgService {
	private static Logger LOGGER = LoggerFactory.getLogger(MemberMsgServiceImpl.class);

	@Resource
	private BaseManager baseMgr;
	@Resource
	private TemplateService velocityService;
	@Resource
	private EnvParameters envParameters;
	@Resource
	private MailService mailService;
	@Resource
	private SmsService smsService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.membermsg.service.MemberMsgService#markDelete(java.lang.Long)
	 */
	@Override
	@Transactional(readOnly = false)
	public void markDelete(Long msgId) {
		MemberMsg msg = (MemberMsg) baseMgr.get(MemberMsg.class, msgId);
		msg.setStatus(MemberMsg.STATUS.DELETED.getValue());
		baseMgr.update(msg);
		// 连同MAIL/SMS一并移除
		String hql = null;
		if (msg.getSendType().equals(MemberMsgTemplate.SEND_TYPE.MAIL.getValue())) {
			hql = "delete from MailTemp where memberMsg.id=?";
		} else {
			hql = "delete from SmsTemp where memberMsg.id=?";
		}
		baseMgr.executeHql(hql, new Object[] { msg.getId() });

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.membermsg.service.MemberMsgService#saveMsg(com.yaodian100.ec.membermsg.entity.MemberMsg)
	 */
	@Override
	@Transactional(readOnly = false)
	public MemberMsg saveMsg(MemberMsg msg) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		MemberMsgTemplate template = (MemberMsgTemplate) baseMgr.get(MemberMsgTemplate.class, msg.getTempId());

		if (msg.getSendType().equals(MemberMsgTemplate.SEND_TYPE.MAIL.getValue())) {
			msg.setContent(template.getMailContent());
		} else {
			msg.setContent(template.getSmsContent());
		}

		String[] orders = msg.getSuccess().split(",");

		String success = "";
		String unsuccess = msg.getUnsuccess();
		if (unsuccess == null) {
			unsuccess = "";
		}
		for (String orderId : orders) {

			try {
				Map<String, Object> context = new HashMap<String, Object>();
				Orders order = (Orders) baseMgr.get(Orders.class, orderId);
				if (order == null) {
					throw new Exception("order is not exist!");
				}

				Member member = (Member) baseMgr.get(Member.class, order.getMemberId());
				// customize
				String memberName = order.getMemberName();
				if (memberName == null || memberName.length() == 0) {
					memberName = order.getLoginId();
				}
				context.put("baseHref", ServerValue.getFrontHostname());
				context.put("memberName", memberName);
				context.put("memberId", order.getMemberId());
				context.put("receiverMobile", order.getReceiverMobile());
				context.put("receiverProvince", order.getReceiverProvince());
				context.put("receiverArea", order.getReceiverArea());
				context.put("receiverCity", order.getReceiverCity());
				context.put("receiverAddr", order.getReceiverAddr());
				context.put("email", member.getEmail());
				context.put("orderProduct", order.getOrderProduct());
				context.put("orderId", order.getOrderId());
				context.put("mobile", member.getMobile());
				context.put("currentDate", sdf.format(new Date()));
				context.put("bonus", msg.getBonus().floatValue());
				context.put("coupon", msg.getCoupon().floatValue());
				context.put("orderObj", order);
				context.put("memberObj", member);
				context.put("msgObj", msg);

				if (msg.getSendType().equals(MemberMsgTemplate.SEND_TYPE.MAIL.getValue())) {
					String content = velocityService.formatByStringTemplate(template.getMailContent(), context);
					if (msg.getSendTo().equals("memberReceiver")) {
						MailTemp mt = new MailTemp(template.getSubject(), content, member.getEmail(), null);
						mt.setMemberMsg(msg);
						baseMgr.save(mt);
					} else {
						MailTemp mt = new MailTemp(template.getSubject(), content, order.getReceiverEmail(), null);
						mt.setMemberMsg(msg);
						baseMgr.save(mt);
					}

				} else {
					if ((member.getMobile() == null || member.getMobile().length() == 0)
							&& (order.getReceiverMobile() == null || order.getReceiverMobile().length() == 0)) {
						throw new Exception("member has no mobile number.");
					}
					String mobile = null;
					if (msg.getSendTo().equals("memberReceiver")) {
						mobile = member.getMobile();
						if (mobile == null || mobile.length() == 0) {
							mobile = order.getReceiverMobile();
						}
					} else {
						mobile = order.getReceiverMobile();
					}

					String content = velocityService.formatByStringTemplate(template.getSmsContent(), context);
					SmsTemp st = new SmsTemp();
					st.setStatus("0");
					st.setDestAddress(mobile);
					st.setContent(content);
					st.setOrderId(orderId);
					st.setMemberMsg(msg);
					baseMgr.save(st);
				}
				if (!success.equals("")) {
					success += ",";
				}
				success += orderId;
			} catch (Exception e) {
				if (!unsuccess.equals("")) {
					unsuccess += ",";
				}
				unsuccess += orderId;
			}
		}

		msg.setSuccess(success);
		msg.setUnsuccess(unsuccess);
		baseMgr.save(msg);

		return msg;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.yaodian100.ec.membermsg.service.MemberMsgService#saveOrUpdateTemplate(com.yaodian100.ec.membermsg.entity.
	 * MemberMsgTemplate)
	 */
	@Override
	@Transactional(readOnly = false)
	public MemberMsgTemplate saveOrUpdateTemplate(MemberMsgTemplate template) {
		baseMgr.saveOrUpdate(template);
		return template;
	}

	@Override
	@Transactional(readOnly = false)
	public void moveMsg(MemberMsg msg) {
		try {
			msg.setStatus(MemberMsg.STATUS.SENDING.getValue());
			baseMgr.update(msg);
			if (msg.getSendType().equals(MemberMsgTemplate.SEND_TYPE.MAIL.getValue())) {
				DetachedCriteria dc2 = DetachedCriteria.forClass(MailTemp.class);
				dc2.add(Restrictions.eq("memberMsg.id", msg.getId()));
				Object[] results = baseMgr.findByCriteria(dc2);
				for (Object obj : results) {
					MailTemp mail = (MailTemp) obj;
					Mail newMail = new Mail(mail.getSubject(), mail.getBody(), mail.getTo(), mail.getCc());
					BeanUtils.copyProperties(mail, newMail);
					newMail.setOid(null);
					newMail.setAttachments(null);
					newMail.setInlines(null);
					baseMgr.save(newMail);
				}
				String hql = "delete from MailTemp where memberMsg.id=?";
				baseMgr.executeHql(hql, new Object[] { msg.getId() });
			} else {
				DetachedCriteria dc2 = DetachedCriteria.forClass(SmsTemp.class);
				dc2.add(Restrictions.eq("memberMsg.id", msg.getId()));
				Object[] results = baseMgr.findByCriteria(dc2);
				for (Object obj : results) {
					SmsTemp sms = (SmsTemp) obj;
					smsService.sendSms(sms.getDestAddress(), sms.getContent(), sms.getOrderId());
				}
				String hql = "delete from SmsTemp where memberMsg.id=?";
				baseMgr.executeHql(hql, new Object[] { msg.getId() });
			}

			msg.setStatus(MemberMsg.STATUS.SUCCESS.getValue());
			baseMgr.update(msg);
		} catch (RuntimeException e) {
			String execLog = StringUtils.printExecption(null, e);
			LOGGER.error(execLog);
			msg.setStatus(MemberMsg.STATUS.FAILED.getValue());
			baseMgr.update(msg);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void sendNotDeliverMsg(String orderId, String productIds) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Orders order = (Orders) baseMgr.get(Orders.class, orderId);
		Member member = (Member) baseMgr.get(Member.class, order.getMemberId());
		String[] productIdSplit = productIds.split(",");
		DetachedCriteria dc = DetachedCriteria.forClass(Product.class);
		dc.add(Restrictions.in("productId", productIdSplit));
		Object[] products = baseMgr.findByCriteria(dc);
		Map<String, Object> contentMap = new HashMap<String, Object>();
		contentMap.put("memberName", member.getLoginId());
		contentMap.put("orderId", orderId);
		contentMap.put("products", products);
		contentMap.put("orderDate", sdf.format(order.getOrderDt()));
		contentMap.put("contextPath", ServerValue.getFrontContextPath());
		contentMap.put("basehref", "http://" + order.getDomainSrc());
		Mail mail = velocityService.formatToMail("order_no_stock", contentMap);

		mail.setFrom(envParameters.getEmailFromSystem());
		mail.setTo(order.getReceiverEmail());

		mailService.save(mail);

		if (member.getMobile() != null && member.getMobile().length() > 0) {
			String productStr = "";
			for (Object obj : products) {
				Product prod = (Product) obj;
				if (productStr.length() != 0) {
					productStr += "、";
				}
				productStr += prod.getProductName();
			}

			String smsMsg = "耀点100用户您好：您的订单编号 " + orderId + "，" + productStr + "目前暂无库存。调货处理时间约为4~6个工作天，"
					+ "您若因时效性需要修改订单或有任何疑问，请致电客服热线4001-168-100，谢谢！";
			smsService.sendSms(member.getMobile(), smsMsg, order.getOrderId());
		}
	}

	public static void main(String[] args) {
		BigDecimal a = new BigDecimal(2.54);
		System.out.println(a.setScale(1, BigDecimal.ROUND_HALF_EVEN).floatValue());

	}
}
